import axios from 'axios';
import AsyncStorage from '@react-native-community/async-storage';
import {replace} from './rootNavigation';
import toastShow from './toastShow';
const service = axios.create({
  baseURL: '',
  timeout: 5000,
});
service.interceptors.request.use(
  async config => {
    if (config.method?.toUpperCase() === 'GET') {
      config.params = config.data;
    }
    const domain = (await AsyncStorage.getItem('domain')) || 'admincs.07n.cn';
    if (domain) {
      config.url = 'https://' + domain + config.url;
    }
    const token = await AsyncStorage.getItem('token');
    if (token) {
      config.headers['authorization'] = 'Bearer ' + token;
    }
    const store_id = await AsyncStorage.getItem('store_id');
    if (store_id) {
      config.headers['Storeid'] = store_id;
    }
    return config;
  },
  error => {
    console.log(error); // for debug
    return Promise.reject(error);
  },
);

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data;
    res.message = res.msg;
    if (
      res.code === 200 ||
      res.code === 1013 ||
      res.code === 1014 ||
      res.code === 1112
    ) {
      return Promise.resolve(res);
    } else {
      if (res.code === 1002 || res.code === 10012) {
        console.log('登录状态失效');
        AsyncStorage.removeItem('token');
        replace('Login');
        return;
      } 
      toastShow(res.message)
      return Promise.reject(new Error(res.message || 'Error'));
    }
  },
  error => {
    console.log('err' + error); // for debug
    console.log('域名错误');
    return Promise.reject(error);
  },
);

export default service;
